from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed

from api.models import User
from ext import http_code


class ParamAuthentication(BaseAuthentication):
    def authenticate(self, request):
        token = request.query_params.get("token")
        if not token:
            return None
        user_object = User.objects.filter(token=token).first()
        print("ParamAuthentication", token, user_object)
        if user_object:
            return user_object, token
        return None

    def authenticate_header(self, request):
        return "API"


class HeaderAuthentication(BaseAuthentication):
    def authenticate(self, request):
        token = request.META.get("HTTP_AUTHORIZATION")
        if not token:
            return None
        user_object = User.objects.filter(token=token).first()
        print("HeaderAuthentication", token, user_object)
        if user_object:
            return user_object, token
        return None

    def authenticate_header(self, request):
        return "API"


class NoAuthentication(BaseAuthentication):
    def authenticate(self, request):
        raise AuthenticationFailed({"code": http_code.ERROR_AUTH, "message": "用户认证失败"})

    def authenticate_header(self, request):
        return "API"
